package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.anotation.CheckUserType;
import com.example.demo.common.anotation.LogExecutionTime;
import com.example.demo.common.enums.CodeEnum;
import com.example.demo.common.exception.BaseRuntimeException;
import com.example.demo.common.result.R;
import com.example.demo.service.impl.MyAsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController("/exbliba")
public class ExclibaController {

    @Autowired
    private MyAsyncService myAsyncService;

    /**
     * 异步调用测试
     * @return
     */
    @GetMapping("/trigger-async")
    public String triggerAsyncMethod(@RequestParam("name")String name, @RequestParam("time")Long time) {
        myAsyncService.asyncMethod(time,name);
        return "async start now";
    }

    /**
     * 异常测试
     * @param name
     * @param time
     * @return
     */
    @GetMapping("/throwExc")
    public R<String> triggerAsyncMethodResult(@RequestParam("name")String name, @RequestParam("time")Long time) {
        if(time<10000L){
            throw new BaseRuntimeException(CodeEnum.FAILURE.getCode(),"time参数小于10000");
        }
        return R.success("成功");
    }

    /**
     * 切面测试
     * @param time
     * @return
     */
    @GetMapping("/aopTest")
    @LogExecutionTime
    public R<String> aopTest(@RequestParam(value = "time",defaultValue = "1000")Long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return R.success("成功");
    }

    /**
     * 切入点测试
     * @param time
     * @return
     */
    @GetMapping("/aopTest2")
    @CheckUserType
    public R<String> aopTest2(@RequestParam(value = "time",defaultValue = "1000")Long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return R.success("成功");
    }

    /**
     * json测试
     * @param json
     * @return
     */
    @GetMapping("/jsonTest3")
    public R<String> aopTest2(@RequestParam String json) {

        JSONObject salespriceJson = JSONObject.parseObject(json);
        if(Boolean.TRUE.equals(salespriceJson.get("state"))){
            JSONObject o = (JSONObject) salespriceJson.get("info");
            Boolean isActualPrice = (Boolean) o.get("isActualPrice");
            return R.success("success"+isActualPrice);
        }
        return R.success("没有");
    }


}
